﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Extensions;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Organizations.Caching;
using Core.Identity.Organizations.Dtos;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Organizations.Features.Queries.GetAll;

/// <summary>
/// 查询全部组织机构
/// </summary>
public class GetAllOrganizationsQuery : ICacheableRequest<Result<IEnumerable<OrganizationDto>>>
{
    /// <summary>
    /// 唯一标识
    /// </summary>
    public Guid? Id { get; set; } = Guid.Empty;

    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => OrganizationsCacheKey.GetOrganizationsById(Id?.ToString());
    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => OrganizationsCacheKey.Tags;
}

public class GetAllOrganizationsQueryHandler :
         IRequestHandler<GetAllOrganizationsQuery, Result<IEnumerable<OrganizationDto>>>
{
    private readonly IIdentityDbContext _context;

    public GetAllOrganizationsQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<Result<IEnumerable<OrganizationDto>>> Handle(GetAllOrganizationsQuery request, CancellationToken cancellationToken)
    {
        return await Result<IEnumerable<OrganizationDto>>
            .SucceedAsync((await _context.Organizations
            .AsNoTracking()
            .WhereIf(request.Id != Guid.Empty, x => x.Id == request.Id)
            .OrderByDescending(x => x.Sort)
            .ToListAsync(cancellationToken))
            .Adapt<IEnumerable<OrganizationDto>>());
    }
}
